import neo
from handlers import handler
import handlers
import sys,socket
from Tkinter import *
import tkMessageBox,tkFileDialog
from threading import Thread
from gallery_downloader import GD

dir=".\\"



def select_download_dir():
	global log,dir
	dir=tkFileDialog.askdirectory()
def start_download():
	global f,url_field,dir,thread_field
	url=url_field.get()
	thread_num=int(thread_field.get())
	try:
		hd=handlers.get_handler(url)
	except:
		tkMessageBox.showwarning("unknown url","the url is not supported. Please check out the list of supported gallery.")
		return
	gd=GD(url=url,dir=dir,thread_num=thread_num,
			   handler=hd)
	t=Thread(target=gd.start_download)
	t.daemon=True
	t.start()


socket.setdefaulttimeout(15)

root = Tk()
root.resizable(width=FALSE, height=FALSE)
f=Frame(root)

Label(f,text="url:").grid(row=0,column=0)
url_field=Entry(f,width=60)
url_field.grid(row=0,column=1)

Label(f,text="thread number:").grid(row=0,column=2)
thread_field=Entry(f,width=10)
thread_field.grid(row=0,column=3)
thread_field.insert(0,"10")

Button(f,text="download to",command=select_download_dir).grid(row=0,column=4)
Button(f,text="start download",command=start_download).grid(row=0,column=5)


scrollbar=Scrollbar(f)
scrollbar.grid(row=1,column=6,sticky=S+N)

log=Text(f,width=100,yscrollcommand=scrollbar.set)

log.grid(row=1,column=0,columnspan=6)
f.pack()

def logger():
	global log
	write_log = handler.handler.write_log
	def write_log_and_update_box(self,msg):
		write_log(self,msg)
		log.insert(END,msg+"\n")
		log.see(END)
	return write_log_and_update_box

handler.handler.write_log=logger()



root.mainloop()
